<?php

class XiangguanWidget extends HomeAction{

	//相关文章

	//参数：
	//$data[l]调用条数
	//$data[t]栏目ID
	//$data[tags]TAG标签

	Public function render($data){
		//数据过滤

		//TAG不存在或为空直接返回
		if(!isset($data['tags']) || empty($data['tags'])){
				return null;
		}

		$tags=$data['tags'];
		$limit=(isset($data['l']))?$data['l']:null;
		$types=(isset($data['t']))?$data['t']:null;
		$id=$this->_get('id');


		//建立缓存KEY值
		$key='xiangguan'.$id.$tags.$types.$limit;


		$cache=S($key);		//将缓存赋到$cache

		if(!empty($cache)){
			$list=$cache;
		}else{

			//拼装相关内容查询条件
			$tags=trim($tags);	$tags=trim($tags,',');

			if(substr_count($tags,',')>=1){
				$tags=explode(',',$tags);	//如果多个TAG则拆分成数组
				$j=count($tags);			//统计TAG数量
				//过滤空TAG标签
				for($i=0;$i<$j;$i++){
					$tags[$i]=trim($tags[$i]);
					if(empty($tags[$i])){unset($tags[$i]);}
				}

				$j=count($tags);			//重新统计TAG数量
				if($j>1){
					//获得根据TAG查询相关文章的条件
					for($i=0;$i<$j;$i++){
						$arr[]=array('like','%'.$tags[$i].'%');
					}
					$arr[$j]='or';

					$sql['where']['title']=$arr;			
				}else{
					$sql['where']['title']=array('like','%'.implode(',',$tags).'%');
				}

			}else{
				$sql['where']['title']=array('like','%'.$tags.'%');
			}

			//查询条件
			if($types!=null){
				if(is_numeric($types)){
					$sql['where']['typeid']=$types;
				}
				if(is_string($types) && strlen($types)>1){
					$sql['where']['typeid']=array('in',$types);
				}
			}

			$sql['limit']=$data['l'];
			$sql['where']['id']=array('neq',$id);	//ID不等于自己，过滤当前文章
			$sql['field']='id,title,typeid,catid';

			//查询相关内容
			$article=M('Article');
			$article->where($sql['where']);
			$article->limit($sql['limit']);
			$article->field($sql['field']);
			$list=$article->query('select %FIELD% from %TABLE%  %WHERE% order by rand() %LIMIT%',true);

			$list=$this->_url($list);

			//存入缓存
			S($key,$list,(F('cachetime')*3));


		}

		$this->assign('list',$list);	//输出相关文章
		$this->display(dirname(__FILE__).'/Xiangguan.html');	//输出到前台模板目录widget_xiangguan.html模板中

	}

}